﻿using System.Text;
using System.Security.Claims;
using Fortunate.Common.Global;
using System.Security.Principal;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using Fortunate.Application.Entities;

namespace Fortunate.Common.Helper
{
    public class TokenHelper
    {
        public string GetToken(Users users)
        {
            // 1. 定义需要使用到的Claims
            var claims = new[]
            {
                new Claim("UsersName", users.Name),
                new Claim("UsersID", users.Id.ToString()),
            };
            // 2. 从 appsettings.json 中读取SecretKey
            var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(FortunateGlobalContext.JwtSettings.SecretKey));
            // 3. 选择加密算法
            var algorithm = SecurityAlgorithms.HmacSha256;
            // 4. 生成Credentials
            var signingCredentials = new SigningCredentials(secretKey, algorithm);
            // 5. 根据以上，生成token
            var jwtSecurityToken = new JwtSecurityToken(
                issuer: FortunateGlobalContext.JwtSettings.Issuer,//Issuer
                audience: FortunateGlobalContext.JwtSettings.Audience,//Audience
                claims:claims,//Claims,
                notBefore: DateTime.Now,//notBefore
                expires:DateTime.Now.AddDays(1),//expires
                signingCredentials:signingCredentials//Credentials
            );
            // 6. 将token变为string
            var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
            return token;

        }

        /// <summary>
        /// 解析Principal
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        private static ClaimsPrincipal GetPrincipal(string token)
        {

            var tokenHandler = new JwtSecurityTokenHandler();
            var jwtToken = tokenHandler.ReadToken(token) as JwtSecurityToken;
            if (jwtToken == null)
            {
                return null;
            }
            var symmetricKey = Convert.FromBase64String("");
            var validationParams = new TokenValidationParameters()
            {
                RequireExpirationTime = true,
                ValidateIssuer = false,
                ValidateAudience = false,
                IssuerSigningKey = new SymmetricSecurityKey(symmetricKey),
            };
            SecurityToken securityToken;
            try
            {
                var pincipal = tokenHandler.ValidateToken(token, validationParams, out securityToken);
                return pincipal;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        
        /// <summary>
        /// 验证Principal
        /// </summary>
        /// <param name="token"></param>
        public static bool ValidateToken(string token, out IPrincipal LoginPrincipal)
        {
            var principal = GetPrincipal(token);
            LoginPrincipal = null;
            if (principal == null) return false;

            var identity = principal.Identity as ClaimsIdentity;
            if (identity == null)
            {
                return false;
            }
            if (!identity.IsAuthenticated)
            {
                return false;
            }
            LoginPrincipal = principal;

            return true;
        }
    }
}
